# coding: utf-8

'''
用户中心, 获取token模块
'''

import sys
import time
import hashlib
import requests


class User_Center():

    def __init__(self, server=""):
        if not server:
            return None
        self.server = server

    def _buildSignature(self, param_list):
        param_list.sort()
        s = "".join([str(x) for x in param_list])
        signature = hashlib.sha1(s.encode('utf-8')).hexdigest().upper()
        return signature.strip()

    def _get_timestamp(self):
        return str(int(time.time()))

    def _get_md5_hash(self, express):
        m = hashlib.md5()
        m.update(b'%s' % express)
        return m.hexdigest()

    def _get_flush_token(self, usr, pwd, clientId, subsystemId, timestamp):
        url = self.server + "/rest/v2/user/login"

        post_params = {
            "clientId" : clientId,
            "subsystemId" : subsystemId,
            "timestamp" : timestamp,
            "account" : usr,
            "password" : pwd
        }
        # print post_params.values()
        post_params["signature"] = self._buildSignature(post_params.values())

        flush_ret = requests.post(url, post_params).content
        # print '....', flush_ret
        if '"message":"操作成功"' in flush_ret:
            flushToken = flush_ret.split('"flushToken":"')[1].split('"')[0]
            return flushToken
        else:
            print "FAIL to login: \n%s" % flush_ret
            sys.exit(1)

    def get_access_token(self, usr, pwd, clientId, subsystemId='2'):
        # 登录获取flush token, 然后换到access token
        timestamp = self._get_timestamp()
        pwd = self._get_md5_hash(pwd)
        flushtoken = self._get_flush_token(usr, pwd, clientId, subsystemId, timestamp)

        url = self.server + "/rest/v2/token/get_access_token"
        post_params = {
            "clientId" : clientId,
            "subsystemId" : subsystemId,
            "timestamp" : timestamp,
            "flushToken" : flushtoken
        }

        post_params["signature"] = self._buildSignature(post_params.values())

        access_ret = requests.post(url, post_params).content
        if '"message":"操作成功"' in access_ret:
            # print 'ret ac token', access_ret
            token = access_ret.split('"accessToken":"')[1].split('"')[0]
            return token
        else:
            print "FAIL to get token: \n%s" % access_ret
            sys.exit(1)

    def validate_access_token(self, clientId, subsystemId, timestamp, accessToken):
        url = self.server + "/rest/v2/token/validate_access_token"
        
        post_params = {
            "clientId" : clientId,
            "subsystemId" : subsystemId,
            "timestamp" : timestamp,
            "accessToken" : accessToken
        }
        post_params["signature"] = self._buildSignature(post_params.values())
        header = {'Connection':'close'}
        validate_token = requests.post(url, post_params, headers=header).content
        # print 'validate_token : ', validate_token
        return validate_token

    def refresh_access_token(self, clientId, subsystemId, timestamp, accessToken):
        url = self.server + "/rest/v2/token/refresh_access_token"
        post_params = {
            "clientId" : clientId,
            "subsystemId" : subsystemId,
            "timestamp" : timestamp,
            "accessToken" : accessToken
        }
        post_params["signature"] = self._buildSignature(post_params.values())
        header = {'Connection' : 'close'}
        refresh_result = requests.post(url, post_params, headers=header).content
        return refresh_result
        # print 'refresh_token : ', refresh_token
        # token = refresh_token.split('"')[13]
        # return token

    def logout(self, clientId, subsystemId, accessToken):
        timestamp = self._get_timestamp()
        post_params = {
            "clientId" : clientId,
            "subsystemId" : subsystemId,
            "timestamp" : timestamp,
            "accessToken" : accessToken
        }

        post_params["signature"] = self._buildSignature(post_params.values())

        url = self.server + "/rest/v2/user/logout"
        header = {'Connection' : 'close'}
        log_out = requests.post(url, post_params, headers=header).content
        return "log_out : %s" % log_out



if __name__ == '__main__':
    # server = 'http://172.18.10.67:8080' # UAT / 39.98.251.101
    server = 'http://uc.hivoice.cn'
    usr = 'dakangz'
    pwd = 'unisound'

    clientId = pwd
    subsystemId = '2' # 开发者网站默认2
    
    uc = User_Center(server)
    print uc.get_access_token(usr, pwd, clientId)